import React, { useState, useEffect, useRef } from 'react';
import './LoadingPage.css';

const LoadingPage = () => {
  const [progress, setProgress] = useState(0);
  const [currentStatus, setCurrentStatus] = useState(0);
  const pathContainerRef = useRef(null);
  const characterRef = useRef(null);
  
  // 状态文本 - 适合1.5秒加载的状态数量
  const statusMessages = [
    "准备中...",
    "加载资源...",
    "处理数据...",
    "完成！"
  ];
  
  useEffect(() => {
    // 调整时间间隔，确保1.5秒内完成
    const interval = setInterval(() => {
      // 每次增加的进度值适合1.5秒加载
      const increment = Math.random() * 10 + 3;
      const newProgress = Math.min(progress + increment, 100);
      setProgress(newProgress);
      
      // 更新角色位置
      if (pathContainerRef.current && characterRef.current) {
        const containerWidth = pathContainerRef.current.offsetWidth - 40;
        const position = (containerWidth * newProgress) / 100;
        characterRef.current.style.left = `${position}px`;
      }
      
      // 更新状态文本
      const newStatus = Math.min(Math.floor(newProgress / 33), statusMessages.length - 1);
      if (newStatus !== currentStatus) {
        setCurrentStatus(newStatus);
        
        // 状态变化动画
        const statusElement = document.querySelector('.status-display');
        if (statusElement) {
          statusElement.classList.add('pulse');
          setTimeout(() => statusElement.classList.remove('pulse'), 300);
        }
      }
      
      // 加载完成（1.5秒内）
      if (newProgress >= 100) {
        clearInterval(interval);
      }
    }, 50); // 调整间隔时间，配合1.5秒总时长
    
    return () => clearInterval(interval);
  }, [progress, currentStatus]);
  
  return (
    <div className="loading-container">
      <h1 className="loading-title">
        <span>加</span><span>载</span><span>中</span><span>...</span>
      </h1>
      
      <div className="path-container" ref={pathContainerRef}>
        <div className="path"></div>
        <div className="path-mark"></div>
        <div className="path-mark"></div>
        <div className="path-mark"></div>
        <div className="path-mark"></div>
        <div className="path-mark"></div>
        <div className="path-end"></div>
        
        <div className="walking-character" ref={characterRef}>
          <div className="character-head"></div>
          <div className="character-body"></div>
          <div className="character-arms">
            <div className="character-arm arm-left"></div>
            <div className="character-arm arm-right"></div>
          </div>
          <div className="character-legs">
            <div className="character-leg leg-left"></div>
            <div className="character-leg leg-right"></div>
          </div>
        </div>
      </div>
      
      <div className="status-display">{statusMessages[currentStatus]}</div>
      <p className="loading-message">请稍候，我们正在为您准备最佳体验</p>
    </div>
  );
};

export default LoadingPage;
